#!/usr/bin python3
# -*- encoding: utf-8 -*-
"""
@author: 关河九州
@contact: 
@software: PyCharm
@file: member_api
@time: 2022/2/28 14:13
"""
import allure
from jsonpath import jsonpath

from base.base_api import BaseApi
from common.wrapper import api_call

""" =============== 成员模块的单接口封装 =============== """


class MemberApi(BaseApi):

    @api_call
    def login_api(self, user=BaseApi().account['user'],
                  pwd=BaseApi().account['pwd'],
                  grant=BaseApi().account['grant'],
                  client_id=BaseApi().account['client_id'],
                  client_secret=BaseApi().account['client_secret']):
        """
        登录接口
        :param user:
        :param pwd:
        :param grant:
        :param client_id:
        :param client_secret:
        :return:
        """
        api = self.conf_data['member_api']['login']
        data = {
            'url': self.host + api,
            'method': 'post',
            'headers': self.headers,
            'params': {
                'username': user,
                'password': pwd,
                'grant_type': grant,
                'client_id': client_id,
                'client_secret': client_secret
            }
        }
        response = self.send_api(data)
        return response

    @allure.step('step:调用获取登录结果api')
    def get_login_data(self, user=BaseApi().account['user'],
                       pwd=BaseApi().account['pwd'],
                       grant=BaseApi().account['grant'],
                       client_id=BaseApi().account['client_id'],
                       client_secret=BaseApi().account['client_secret']
                       ):
        """
        提取处理登录响应数据
        :param user:
        :param pwd:
        :param grant:
        :param client_id:
        :param client_secret:
        :return:
        """
        response = self.login_api(user, pwd, grant, client_id, client_secret)
        res = response.json()
        login_data = dict()
        login_data['access_token'] = self.get_token(response)
        login_data['member_id'] = jsonpath(res, '$..id')[0]
        login_data['username'] = jsonpath(res, '$..username')[0]
        return login_data

    @api_call
    def recharge_api(self, member_id: int, amount: float, token):
        """
        账户充值接口
        :param member_id: 用户id
        :param amount: 充值金额（最多小数点后两位）
        :param token: token
        :return:
        """
        api = self.conf_data['member_api']['recharge']
        data = {
            'url': self.host + api,
            'method': 'post',
            'headers': self.headers,
            'json': {
                'member_id': member_id,
                'amount': amount
            }
        }
        # 添加token
        data['headers'].update({'Authorization': token})
        # 发送请求
        response = self.send_api(data)
        return response
